package com.siecom.module;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.Log;

import com.siecom.algorithm.des.AlgorithmUtil;
import com.siecom.algorithm.sm.SMUtil;
import com.siecom.constconfig.ConstDefine;
import com.siecom.constconfig.ErrorDefine;
import com.siecom.hostservice.MainActivity;
import com.siecom.tool.ByteTool;
import com.siecom.tool.FileUnits;
import com.siecom.tool.LogUtil;
import com.siecom.tool.Timer;
import com.siecom.transport.handler.KeyBoardHandler;

import java.io.IOException;
import java.util.LinkedHashSet;
import java.util.List;

import static com.siecom.hostservice.MainActivity.context;

/**
 * Created
 */

public class KeyBoardRunnable extends ModuleRunnable {
    private final static String TAG = "KeyBoardRunnable";
    public static CipherKeyBoardModule keyBoardModule = CipherKeyBoardModule.getInstance();
    private String cardNo;
    private static String masterKeyIndex;
    private String workKeyIndex;
    private String pwdLen;
    private String timeOutSec;
    private int encryptMode;
    private boolean isEncrypted;
    private int enterFre;
    private int inputTimes = 1;

    byte[] pinBlockTemp = new byte[16];
    private String tempPwdStr = "";

    private Timer timer = null;

    public static PinEntryBroadcastReceiver mPinReceiver  ;

    public boolean isInputting() {

        if (alreadyInputlength > 0 && runFlag) {

            return true;
        }
        return false;
    }

    public int getAlreadyInputlength() {

        return alreadyInputlength;
    }

    private int alreadyInputlength = 0;

    public KeyBoardRunnable (){

    }


    public KeyBoardRunnable(String cardNo, String masterKeyIndex, String workKeyIndex, String pwdLen, String timeOutSec, int encryptMode,final int inputTimes, DeviceCallback callback, boolean isOnMain, boolean isEncrypted) {

        this.cardNo = cardNo;
        this.masterKeyIndex = masterKeyIndex;
        this.workKeyIndex = workKeyIndex;
        this.pwdLen = pwdLen;
        this.timeOutSec = timeOutSec;
        this.encryptMode = encryptMode;
        this.callback = callback;
        this.isOnMain = isOnMain;
        this.isEncrypted = isEncrypted;
        this.inputTimes = inputTimes;
        LogUtil.e(TAG,"mPinReceiver=" + mPinReceiver + " ---- inputTimes ==" + inputTimes);
        if(mPinReceiver == null ){
            mPinReceiver = new PinEntryBroadcastReceiver();
            IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction("com.pos.pinentry");
            context.registerReceiver(mPinReceiver,intentFilter);
            LogUtil.e(TAG,"注册了广播 mPinReceiver=" + mPinReceiver);
        }


    }

    public void stopRun() {
        this.runFlag = false;
        keyBoardModule.setStopRun(true);
    }
    public static void unregisterPinEntryReceiver(){
        if(mPinReceiver != null){
            context.unregisterReceiver(mPinReceiver);
            mPinReceiver = null;
        }

    }

    @Override
    public void run() {
        //设置使用的密钥
        synchronized (this) {

            byte[] pinBlock = new byte[16];
            int res = -1;

            boolean runFlag = true;  // 接受密码键盘明文输入的值。

            com.pos.utils.PinContext ctx = new com.pos.utils.PinContext();

            byte [] background = new byte[3];
            byte [] font = new byte [4];
            byte [] prompt = "请输入密码:".getBytes();
            background[0] = (byte)0xff;//R
            background[1] = (byte)0xff;//G
            background[2] = (byte)0xff;//B
            font[0] = (byte)0xff;//R
            font[1] = (byte)0x00;//G
            font[2] = (byte)0xff;//B
            font[3] = 20;//text size(dp)
            ctx.setPromptLength(prompt.length);
            ctx.setFontLength(font.length);
            ctx.setBackgroundLength(background.length);
            ctx.setPrompt(prompt);
            ctx.setFont(font);
            ctx.setBackground(background);

            //设置卡号或传输码
            byte i = (byte) Integer.parseInt(workKeyIndex); //秘钥索引值为 0-5
            if(i < 0 || i >5){
                i = 0;
            }
            final byte index = i; //秘钥索引号
            int mLen = Integer.parseInt(pwdLen);
            if(mLen > 16 || mLen < 4){
                mLen = 16;
            }
            byte maxLen = (byte)mLen; //秘钥最大长度
            byte minLen = 0x04;
            if (TextUtils.isEmpty(cardNo)) cardNo = "000000000000";
            byte cardNoByts[] = cardNo.getBytes();
            byte cardNoLen = (byte) cardNoByts.length;
            byte mark = 0;  // 0  显示amount   1  不显示amount
            byte amount[] = " ".getBytes();
            amount = null;
            byte waitTimeSec = Byte.parseByte(timeOutSec);  //超时等待时间
            int j = 0;
            /**
             *mode   0x20| 0x04  密码不足最小长度 返回错误        0x20 密码不足最小长度 不返回   0显示带金额的输入界面
             */
            byte mode = 0x20|0x04;
            LogUtil.e(TAG,"encryptMode ==" + encryptMode);

            //密钥长度过长直接返回错误
            if (mLen > 14){
                if (encryptMode == 0 || encryptMode == 4 || encryptMode == ConstDefine.KEY_3DES || encryptMode == ConstDefine.KEY_SM ){
                    Bundle bundle = new Bundle();
                    bundle.putInt("code", ErrorDefine.PWD_LENGTH_ERR);
                    bundle.putString("message", ErrorDefine.getErrorDescribe(ErrorDefine.PWD_LENGTH_ERR));
                    deliverResult(callback, DeviceInterface.Result.ERROR, bundle, isOnMain);
                    return;
                }
            }

            //软解密  0 国密   4 国际 软算
            if (encryptMode == 0 || encryptMode == 4){
                {
                    String keyWork ,workKeyName;
                    if (encryptMode == 4){ //3DES
                        workKeyName = DeviceInterface.keyInfoUtil.getWorkKeyName(1,index + 10);
                    }else {
                        workKeyName = DeviceInterface.keyInfoUtil.getWorkKeyName(1,index);
                    }
                    keyWork = DeviceInterface.keyInfoUtil.getKey(workKeyName);

                    if (TextUtils.isEmpty(keyWork)){
                        Bundle bundle = new Bundle();
                        bundle.putInt("code", ErrorDefine.KEY_NO_WORK_KEY);
                        bundle.putString("message", ErrorDefine.getErrorDescribe(ErrorDefine.KEY_NO_WORK_KEY));
                        deliverResult(callback, DeviceInterface.Result.ERROR, bundle, isOnMain);
                        return;
                    }
                    if (timer != null) timer.setTimOut();
                    else timer = new Timer(Integer.parseInt(timeOutSec)*1000L);
                    timer.setTimeOutMs(Integer.parseInt(timeOutSec)*1000L);
                    timer.start();
                    KeyBoardHandler.plainTextInputing = true;
                    if (MainActivity.isWakeUp){
                        try {
                            Thread.sleep(2500);
                            LogUtil.e(TAG,"--sleep 2500");
                            MainActivity.isWakeUp = false;
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    int openRes = MainActivity.getmMainPci().DLL_PciKbOpen();
                    if(openRes != 0){
                        Bundle bundle = new Bundle();
                        bundle.putInt("code", ErrorDefine.KEYBORAD_OPEN_ERR);
                        bundle.putString("message", ErrorDefine.getErrorDescribe(ErrorDefine.KEYBORAD_OPEN_ERR));
                        deliverResult(callback, DeviceInterface.Result.ERROR, bundle, isOnMain);
                    }else {

                        deliverResult(callback, DeviceInterface.Result.START, null, isOnMain);
                        StringBuffer sb = new StringBuffer();
                        int alreadyInputLen = 0;
                        byte[] keyVlaue = new byte[1];
                        while (runFlag){

                            if (timer.timeOut()){
                                Bundle bundle = new Bundle();
                                bundle.putInt("code", ErrorDefine.KEY_TIME_OUT);
                                bundle.putString("message", ErrorDefine.getErrorDescribe(ErrorDefine.KEY_TIME_OUT));
                                deliverResult(callback, DeviceInterface.Result.ERROR, bundle, isOnMain);
                                runFlag = false;
                                MainActivity.getmMainPci().DLL_PciKbClose(); //关闭键盘
                                return;
                            }
                            if(!KeyBoardHandler.plainTextInputing){//取消输入
                                deliverResult(callback, DeviceInterface.Result.ERROR, null, isOnMain);
                                MainActivity.getmMainPci().DLL_PciKbClose(); //关闭键盘
                                LogUtil.e(TAG," 取消了明文输入 DLL_PciKbClose" );
                                return;
                            }
                            SystemClock.sleep(100);
                            res = MainActivity.getmMainPci().DLL_PciKbGetKey(keyVlaue);
                            if(res != 0){
                                Bundle bundle = new Bundle();
                                bundle.putInt("code", ErrorDefine.KEYBORAD_OPEN_ERR);
                                bundle.putString("message", ErrorDefine.getErrorDescribe(ErrorDefine.KEYBORAD_OPEN_ERR));
                                deliverResult(callback, DeviceInterface.Result.ERROR, bundle, isOnMain);
                                return;
                            }
                            if((keyVlaue[0]&0xFF) == 0xFF){
                                continue;
                            }else {
//                                LogUtil.e(TAG, "接收的字符：" + (keyVlaue[0]&0xFF) + "---res =" + res );
                                if(keyVlaue[0] <= 0x39 && keyVlaue[0] >= 0x30){
                                    if(alreadyInputLen < Integer.parseInt(pwdLen)){
                                        sb.append(new String(keyVlaue));
                                        alreadyInputLen ++;
                                        Bundle bundle = new Bundle();
                                        bundle.putInt("flag", 1);
                                        bundle.putInt("data", alreadyInputLen);
                                        deliverResult(callback, DeviceInterface.Result.SUCCEED, bundle, isOnMain);
                                    }

                                }else if(keyVlaue[0] == 0x1C){ //返回 （取消上一次的输入）
                                    if(alreadyInputLen > 0){
                                        LogUtil.e(TAG,"sb==" + sb.toString());
                                        sb = sb.deleteCharAt(alreadyInputLen - 1);

                                        LogUtil.e(TAG,"sb==" + sb.toString());
                                        alreadyInputLen --;

                                        Bundle bundle = new Bundle();
                                        bundle.putInt("flag", 1);
                                        bundle.putInt("data", alreadyInputLen);
                                        deliverResult(callback, DeviceInterface.Result.SUCCEED, bundle, isOnMain);
                                    }
                                    continue;

                                }else if(keyVlaue[0] == 0x1B){  //取消输入
                                    alreadyInputLen = 0;
                                    sb = new StringBuffer();
                                    Bundle bundle = new Bundle();
                                    bundle.putInt("code", ErrorDefine.CANCEL_INPUT);
                                    bundle.putString("message", ErrorDefine.getErrorDescribe(ErrorDefine.CANCEL_INPUT));
                                    deliverResult(callback, DeviceInterface.Result.ERROR, bundle, isOnMain);
                                    runFlag = false;  //结束接收
                                    MainActivity.getmMainPci().DLL_PciKbClose(); //关闭键盘
                                }else if (keyVlaue[0] == 0x0D){  //确认
                                    if(alreadyInputLen >= Integer.parseInt(pwdLen)){
                                        String pinMin = sb.toString();
                                        //校验 弱密钥
                                        if (isWeekPassword(pinMin)){
                                            LogUtil.e(TAG,"isWeekPassword == true");
                                            sb = new StringBuffer();
                                            Bundle bundle = new Bundle();
                                            bundle.putInt("code", ErrorDefine.KEY_WEAK_ERR);
                                            bundle.putString("message", ErrorDefine.getErrorDescribe(ErrorDefine.KEY_WEAK_ERR));
                                            deliverResult(callback, DeviceInterface.Result.ERROR, bundle, isOnMain);
                                            runFlag = false;
                                            MainActivity.getmMainPci().DLL_PciKbClose(); //关闭键盘
                                            return;
                                        }

                                        //第一次输入
                                        if (inputTimes >= 2){
//                                            LogUtil.e(TAG,"pinMin == " + pinMin);
                                            //校验 弱密钥
//                                            if (isWeekPassword(pinMin)){
//                                                LogUtil.e(TAG,"isWeekPassword == ");
//                                                sb = new StringBuffer();
//                                                Bundle bundle = new Bundle();
//                                                bundle.putInt("code", ErrorDefine.KEY_WEAK_ERR);
//                                                bundle.putString("message", ErrorDefine.getErrorDescribe(ErrorDefine.KEY_WEAK_ERR));
//                                                deliverResult(callback, DeviceInterface.Result.ERROR, bundle, isOnMain);
//                                                runFlag = false;
//                                                MainActivity.getmMainPci().DLL_PciKbClose(); //关闭键盘
//                                            } else
                                                {
                                                inputTimes --;
                                                tempPwdStr = sb.toString();
                                                sb = new StringBuffer();
                                                Bundle bundle = new Bundle();
                                                bundle.putInt("flag", 1);
//                                                bundle.putString("data", "please input again");
                                                bundle.putInt("data", 100);
                                                deliverResult(callback, DeviceInterface.Result.SUCCEED, bundle, isOnMain);

                                            }
                                            alreadyInputLen = 0;

                                        }else {  //只有一次输入 或者最后一次输入 返回成功

                                            Bundle bundle = new Bundle();
                                            if (tempPwdStr.isEmpty() || tempPwdStr.equals(sb.toString())){

                                                String key = getPinByLocal(keyWork,index,cardNo,sb.toString(),encryptMode);
                                                LogUtil.e(TAG, " ---- 加密结果 key == " + key);
                                                bundle.putInt("flag", 0);
                                                bundle.putString("data",key);
                                                deliverResult(callback, DeviceInterface.Result.COMPLETED, bundle, isOnMain);
                                            }else { //两次密码输入不一致
                                                bundle.putInt("code", ErrorDefine.ERR_NOT_SAME);
                                                bundle.putString("message", ErrorDefine.getErrorDescribe(ErrorDefine.ERR_NOT_SAME));
                                                deliverResult(callback, DeviceInterface.Result.ERROR, bundle, isOnMain);
                                            }
                                            tempPwdStr = "";
                                            LogUtil.e(TAG,"按了确认 runflag = " + runFlag);
                                            runFlag = false;
                                            MainActivity.getmMainPci().DLL_PciKbClose(); //关闭键盘
                                        }

                                    }

                                }
                            }
//                            LogUtil.e(TAG, "接收的所有字符：" + sb.toString());
                        }

                    }

                }
            }
            else
            if(encryptMode == ConstDefine.KEY_3DES){  //密文 3DES 获取

                deliverResult(callback, DeviceInterface.Result.START, null, isOnMain);

                //mode   0x20| 0x04  密码不足最小长度 返回错误        0x20 密码不足最小长度 不返回   0显示带金额的输入界面
                for (j = 0; j < inputTimes; j++) {
                    LogUtil.e(TAG,"keyIndex == " + index);
                    res = MainActivity.getmMainPci().DLL_PciGetPin(index, minLen, maxLen, cardNoLen, cardNoByts, mode, pinBlock, mark, null, waitTimeSec, ctx);
                    if (res == 0 && inputTimes > 1 && j == 0){
                        Bundle bundle = new Bundle();
                        bundle.putInt("flag", 1);
//                        bundle.putString("data", "please input again");
                        bundle.putInt("data", 100);
                        deliverResult(callback, DeviceInterface.Result.SUCCEED, bundle, isOnMain);
                    }
                    if (j >= 1){
                        if (!ByteTool.bytearrayToHexString(pinBlock,8).equals(ByteTool.bytearrayToHexString(pinBlockTemp,8))) {
                            res = ErrorDefine.ERR_NOT_SAME;
                            break;
                        }
                    }
                    System.arraycopy(pinBlock,0,pinBlockTemp,0,8);

                }


                LogUtil.e(TAG,"res==" + res);
                if (res != 0) {
                    Bundle bundle = new Bundle();

                    if(res == ErrorDefine.ERR_NOT_SAME){
                        bundle.putInt("code", ErrorDefine.ERR_NOT_SAME);
                        bundle.putString("message", ErrorDefine.getErrorDescribe(ErrorDefine.ERR_NOT_SAME));
                    }else if (res == -7007){  //用户取消了输入
                        bundle.putInt("code", ErrorDefine.CANCEL_INPUT);
                        bundle.putString("message", ErrorDefine.getErrorDescribe(ErrorDefine.CANCEL_INPUT));
                    } else if (res == -7009){  //输入超时
                        bundle.putInt("code", ErrorDefine.KEY_TIME_OUT);
                        bundle.putString("message", ErrorDefine.getErrorDescribe(ErrorDefine.KEY_TIME_OUT));
                    }else {
                        bundle.putInt("code", ErrorDefine.SET_ENCRYPT_ERR);
                        bundle.putString("message", ErrorDefine.getErrorDescribe(ErrorDefine.SET_ENCRYPT_ERR));
                    }
                    deliverResult(callback, DeviceInterface.Result.ERROR, bundle, isOnMain);

                    SystemClock.sleep(100);

                    return;
                }else {
                    if(j >= 1 || inputTimes <= 1){
                        Bundle bundle = new Bundle();
                        bundle.putInt("flag", 0);
                        bundle.putString("data", ByteTool.bytearrayToHexString(pinBlock, 8));
                        bundle.putByteArray("pwd", pinBlock);
                        deliverResult(callback, DeviceInterface.Result.COMPLETED, bundle, isOnMain);
                    }


                }

            }else
                if(encryptMode == ConstDefine.KEY_SM){ //国密 SM4
                deliverResult(callback, DeviceInterface.Result.START, null, isOnMain);
//                amount = new byte[14];
//                System.arraycopy("123456.00".getBytes(), 0, amount, 0, "123456.00".getBytes().length);
                for (j = 0; j < inputTimes; j++) {
                    res = MainActivity.getmSm().DLL_SMGetPinSM4K(index, minLen, maxLen, cardNoLen, cardNoByts, mode, pinBlock, mark, null, waitTimeSec, ctx);

                    if (res == 0 && inputTimes > 1 && j == 0){
                        Bundle bundle = new Bundle();
                        bundle.putInt("flag", 1);
//                        bundle.putString("data", "please input again");
                        bundle.putInt("data", 100);
                        deliverResult(callback, DeviceInterface.Result.SUCCEED, bundle, isOnMain);
                    }
                    if (j >= 1){
                        LogUtil.e(TAG,"jjjjjjjjjjjjjjjjjjjjjjjjjj = =" + j);
                        if (!ByteTool.bytearrayToHexString(pinBlock,8).equals(ByteTool.bytearrayToHexString(pinBlockTemp,8))) {
                            LogUtil.e(TAG,"j not same ==" + j);
                            res = ErrorDefine.ERR_NOT_SAME;
                            break;
                        }
                    }
                    System.arraycopy(pinBlock,0,pinBlockTemp,0,8);
                }

                LogUtil.e(TAG,"SM4 res==" + res);
                if (res != 0) {
                    Bundle bundle = new Bundle();

                    if(res == ErrorDefine.ERR_NOT_SAME){
                        bundle.putInt("code", ErrorDefine.ERR_NOT_SAME);
                        bundle.putString("message", ErrorDefine.getErrorDescribe(ErrorDefine.ERR_NOT_SAME));
                    }else if (res == -7007){  //用户取消了输入
                        bundle.putInt("code", ErrorDefine.CANCEL_INPUT);
                        bundle.putString("message", ErrorDefine.getErrorDescribe(ErrorDefine.CANCEL_INPUT));
                    } else if (res == -7009){  //输入超时
                        bundle.putInt("code", ErrorDefine.KEY_TIME_OUT);
                        bundle.putString("message", ErrorDefine.getErrorDescribe(ErrorDefine.KEY_TIME_OUT));
                    }else {
                        bundle.putInt("code", ErrorDefine.SET_ENCRYPT_ERR);
                        bundle.putString("message", ErrorDefine.getErrorDescribe(ErrorDefine.SET_ENCRYPT_ERR));
                    }
                    deliverResult(callback, DeviceInterface.Result.ERROR, bundle, isOnMain);

                    SystemClock.sleep(100);

                    return;
                }else {
                    if (j >= 1 || inputTimes <= 1){
                        Bundle bundle = new Bundle();
                        bundle.putInt("flag", 0);
                        bundle.putString("data", ByteTool.bytearrayToHexString(pinBlock, 16));
                        bundle.putByteArray("pwd", pinBlock);
                        deliverResult(callback, DeviceInterface.Result.COMPLETED, bundle, isOnMain);
                    }


                }

            }
                else { //明文=============================================================================================
                if (timer != null){
                    timer.setTimOut();
                    timer = null;
                }
                timer = new Timer(Integer.parseInt(timeOutSec) *1000L);
                LogUtil.e(TAG,"timeOutsec == " + timeOutSec);
                timer.start();

                KeyBoardHandler.plainTextInputing = true;

                    MainActivity.getmMainPci().DLL_PciKbClose();

                int openRes = MainActivity.getmMainPci().DLL_PciKbOpen();
                if (MainActivity.isWakeUp){
                    try {
                        Thread.sleep(2500);
                        LogUtil.e(TAG,"--sleep 2500");
                        MainActivity.isWakeUp = false;
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                if(openRes != 0){
                    Bundle bundle = new Bundle();
                    bundle.putInt("code", ErrorDefine.KEYBORAD_OPEN_ERR);
                    bundle.putString("message", ErrorDefine.getErrorDescribe(ErrorDefine.KEYBORAD_OPEN_ERR));
                    deliverResult(callback, DeviceInterface.Result.ERROR, bundle, isOnMain);
                }else {

                    deliverResult(callback, DeviceInterface.Result.START, null, isOnMain);
                    StringBuffer sb = new StringBuffer();
                    int alreadyInputLen = 0;
                    byte[] keyVlaue = new byte[1];
                    while (runFlag){
                        if (timer.timeOut()){
                            Bundle bundle = new Bundle();
                            bundle.putInt("code", ErrorDefine.KEY_TIME_OUT);
                            bundle.putString("message", ErrorDefine.getErrorDescribe(ErrorDefine.KEY_TIME_OUT));
                            deliverResult(callback, DeviceInterface.Result.ERROR, bundle, isOnMain);
                            runFlag = false;
                            MainActivity.getmMainPci().DLL_PciKbClose(); //关闭键盘
                            return;
                        }
                        if(!KeyBoardHandler.plainTextInputing){//取消输入
                            deliverResult(callback, DeviceInterface.Result.ERROR, null, isOnMain);
                            MainActivity.getmMainPci().DLL_PciKbClose(); //关闭键盘
                            LogUtil.e(TAG," 取消了明文输入 DLL_PciKbClose" );
                            return;
                        }
                        SystemClock.sleep(100);
                        res = MainActivity.getmMainPci().DLL_PciKbGetKey(keyVlaue);
                        if(res != 0){
                            Bundle bundle = new Bundle();
                            bundle.putInt("code", ErrorDefine.KEYBORAD_OPEN_ERR);
                            bundle.putString("message", ErrorDefine.getErrorDescribe(ErrorDefine.KEYBORAD_OPEN_ERR));
                            deliverResult(callback, DeviceInterface.Result.ERROR, bundle, isOnMain);
                            return;
                        }
                        if((keyVlaue[0]&0xFF) == 0xFF){
                            continue;
                        }else {
                            LogUtil.e(TAG, "接收的字符：" + (keyVlaue[0]&0xFF) + "---res =" + res );
                            if(keyVlaue[0] <= 0x39 && keyVlaue[0] >= 0x30){
                                if(alreadyInputLen < Integer.parseInt(pwdLen)){
                                    sb.append(new String(keyVlaue));
                                    alreadyInputLen ++;
                                    Bundle bundle = new Bundle();
                                    bundle.putInt("flag", 1);
                                    bundle.putInt("data", alreadyInputLen);
                                    deliverResult(callback, DeviceInterface.Result.SUCCEED, bundle, isOnMain);
                                }

                            }else if(keyVlaue[0] == 0x1C){ //返回 （取消上一次的输入）
                                if(alreadyInputLen > 0){
                                    LogUtil.e(TAG,"sb==" + sb.toString());
                                    sb = sb.deleteCharAt(alreadyInputLen - 1);

                                    LogUtil.e(TAG,"sb==" + sb.toString());
                                    alreadyInputLen --;

                                    Bundle bundle = new Bundle();
                                    bundle.putInt("flag", 1);
                                    bundle.putInt("data", alreadyInputLen);
                                    deliverResult(callback, DeviceInterface.Result.SUCCEED, bundle, isOnMain);
                                }
                                continue;

                            }else if(keyVlaue[0] == 0x1B){  //取消输入
                                alreadyInputLen = 0;
                                sb = new StringBuffer();
                                Bundle bundle = new Bundle();
                                bundle.putInt("code", ErrorDefine.CANCEL_INPUT);
                                bundle.putString("message", ErrorDefine.getErrorDescribe(ErrorDefine.CANCEL_INPUT));
                                deliverResult(callback, DeviceInterface.Result.ERROR, bundle, isOnMain);
                                runFlag = false;  //结束接收
                                MainActivity.getmMainPci().DLL_PciKbClose(); //关闭键盘
                            }else if (keyVlaue[0] == 0x0D){  //确认
                                if(alreadyInputLen >= Integer.parseInt(pwdLen)){
                                    runFlag = false;
                                    Bundle bundle = new Bundle();
                                    bundle.putInt("flag", 0);
                                    bundle.putString("data", sb.toString());

                                    deliverResult(callback, DeviceInterface.Result.COMPLETED, bundle, isOnMain);
                                    LogUtil.e(TAG,"按了确认 runflag = " + runFlag);
                                    MainActivity.getmMainPci().DLL_PciKbClose(); //关闭键盘
                                }

                            }
                        }
                        LogUtil.e(TAG, "接收的所有字符：" + sb.toString());
                    }

                }

            }


        }

    }

    @SuppressLint("DefaultLocale")
    private String  getPinByLocal(String workKey, int index, String cardNo, String pin, int encryptMode){

//        String workKey = DeviceInterface.keyInfoUtil.getKey(DeviceInterface.keyInfoUtil.getWorkKeyName(1,index));
        if (TextUtils.isEmpty(cardNo))  cardNo = "000000000000";
        String subCardNo = "";
        if( cardNo.length() < 13){
            subCardNo = cardNo;
        }else {
            subCardNo = cardNo.substring(cardNo.length() -13,cardNo.length()-1);
        }

        StringBuilder finalCardNo = new StringBuilder(subCardNo);
        pin = String.format("%02X",pin.length()) + pin;
        if (encryptMode == 4){  //3DES 算法

            while (finalCardNo.length() < 16){
                finalCardNo.insert(0, "0");
            }
            while (pin.length() < 16){
                pin = pin + "F";
            }

        }else {
            while (finalCardNo.length() < 32){
                finalCardNo.insert(0, "0");
            }

            while (pin.length() < 32){
                pin = pin + "F";
            }

        }

//            LogUtil.e(TAG,"finalCardNo ==" + finalCardNo);
//            LogUtil.e(TAG,"final pin ==" + pin);
        byte xorbt[] = ByteTool.bytesXOR(ByteTool.hexStr2Bytes(finalCardNo.toString()),ByteTool.hexStr2Bytes(pin));
        assert xorbt != null;
        String x98or = ByteTool.byte2hex(xorbt);
//            LogUtil.e(TAG,"x98or ==" + x98or);
        String finalPin;
        if (encryptMode == 4){ //3DES
            byte[] finalPinBytes = AlgorithmUtil.algorithm3DES(1,ByteTool.hexStr2Bytes(workKey),xorbt);
            assert finalPinBytes != null;
            finalPin = ByteTool.byte2hex(finalPinBytes);
        }else { //国密SM4
            finalPin = SMUtil.SM4EncryptECB(x98or,workKey);
        }
        return finalPin;
    }

    /**
     * 对密码进行校验判断，弱密码将返回true，强密码返回false
     *
     * 如果密码是以下几种情况将返回true,即是弱密码：
     * 1.如果密码是admin、
     * 2.密码位数小于等于6位、
     * 3.密码全部是相同的字符（如：aaaaaaa、8888888）、
     * 4.密码全部是空字符、
     * 5.密码全是顺序字符（如：123456、987654、bcdefg、gfedcb）
     */
    public static boolean isWeekPassword(String password) {
        if (!masterKeyIndex.equals("validate")) {
            return false;
        }
        password = password.trim();
        //判断密码是不是特殊的admin
        if ("admin".equalsIgnoreCase(password) || password.length() < 6) {
            return true;
        }
        char[] chPassword = password.toCharArray();
        LinkedHashSet<Character> link = new LinkedHashSet<>();
        StringBuilder buff = new StringBuilder();
        boolean result = false;
        int count = 0;
        for (int i = 0; i < chPassword.length; i++) {
            //判断密码是否是连续的正序或降序数字或字母
            int preNumber = i == 0 ? -999 : chPassword[i - 1] - 0; //前一字符对应的ascii码
            int currentNumber = chPassword[i] - 0;//当前字符对应的ascii码
            int asciiNum = preNumber + currentNumber;
            if ((96 <= asciiNum && asciiNum <= 114) || (130 <= asciiNum && asciiNum <= 180) || (194 <= asciiNum && asciiNum <= 244)) {
                //判断密码的相邻字符是否是正序或降序的数字或字符
                if (Math.abs(preNumber - currentNumber) == 1) {
                    count += 1;
                }
            }
            //处理不重复的字符
            if (!link.contains(chPassword[i])) {
                link.add(chPassword[i]);
                buff.append(chPassword[i]);
            }
        }
        //处理空字符串和密码全是同一字符的
        String resultStr = String.valueOf(buff);
        if (count == chPassword.length - 1 || resultStr.length() <= 1) {
            result = true;
        }
        return result;
    }


    private boolean checkWeakPwd(String pwd){
        if (TextUtils.isEmpty(pwd) || pwd.length() < 6){
            return true;
        }
        byte[] pwdByte = pwd.getBytes();
        //
        for (int i = 0; i < pwdByte.length; i++) {
            if (i == pwd.length() -1)
                break;
            if (pwdByte[i] != pwdByte[i+1]){
                return false;
            }
        }
        return false;
    }


    public class PinEntryBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
//            LogUtil.e("----------------","PinEntryBroadcastReceiver----"+ intent.getAction());
            if (intent.getAction().equals("com.pos.pinentry"))
            {
                int len = intent.getIntExtra("pinLen", 0);
                Log.e("PinLen","PinLen:"+len);//len:0~12  finish:100
                  Intent newIntent = new Intent(context, MainActivity.class);
                  newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  //注意，必须添加这个标记，否则启动会失败
                  context.startActivity(newIntent);
                if(len >0 && len < 20){  //判断长度
                    Bundle bundle = new Bundle();
                    bundle.putInt("flag", 1);
                    bundle.putInt("data", len);
                    deliverResult(callback, DeviceInterface.Result.SUCCEED, bundle, isOnMain);
                }


            }
        }
    }


}
